﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WCITZ.Controllers
{
    public class JoinController : Controller
    {
		WCITZEntities db = new WCITZEntities();

        //
        // GET: /Join/

        public ActionResult Index()
        {
			if (Request.Form.Count==0)
			{
				return View("FO");
			}
			//ViewBag.userName = Request.Form["userName"];
			//ViewBag.tableName = Request.Form["tableName"];

			/*
			 * If such a table does not exist, create it
			 */
			bool found = false;
			foreach (var table in db.Tables)
			{
				if (table.Name == Request.Form["tableName"])
				{
					found = true;
					break;
				}
			}
			if (!found)
			{
				// Create table

				var newTable = new Table();
				newTable.Name = Request.Form["tableName"];

				db.Tables.Add(newTable);
				db.SaveChanges();
			}
			/**/

			/*
			 * If such a player does not exist in the table, create
			 */
			found = false;
			foreach (var player in db.Players)
			{
				if (player.Table1.Name == Request.Form["tableName"] && player.Name == Request.Form["playerName"])
				{
					found = true;
					break;
				}
			}
			if (!found)
			{
				// Create user

				var newPlayer= new Player();
				newPlayer.Name = Request.Form["playerName"];

				foreach (var table in db.Tables)
				{
					if (table.Name == Request.Form["tableName"])
					{
						newPlayer.Table1 = table;
						newPlayer.Result = 1;
					}
				}

				db.Players.Add(newPlayer);
				db.SaveChanges();
			}
			/**/

			ViewData["tableName"] = Request.Form["tableName"];

			/*
			 * Set this player's status as 1 (wating for roll)
			 */
			foreach(var player in db.Players.ToList())
			{
				if (player.Name == Request.Form["playerName"] && player.Table1.Name == Request.Form["tableName"])
				{
					player.Status = 1;

					db.Players.Attach(player);
					db.Entry(player).State = System.Data.EntityState.Modified;
					db.SaveChanges();
				}
			}
			/**/

			ViewData["playerName"] = Request.Form["playerName"];
			ViewData["tableName"] = Request.Form["tableName"];

            return View();
        }

    }
}
